package com.example.clientend.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 读取log文件中生成的会话信息内容，通过字符串匹配获取address和cid
 */
@Component
public class StringMatcher {
    @Value("${path.serviceLogPath}")
    private String logPath;

    public JSONObject readInfo(){
        String cid = "";
        String address = "";
        // cid匹配正则表达式
        Pattern cidPattern = Pattern.compile("-a \".*\" -s \"(.*)\"");
        // address匹配正则表达式
        Pattern addressPattern = Pattern.compile("Login server ok\\((.*)\\)");
        try (BufferedReader reader = new BufferedReader(new FileReader(logPath))) {
            String currentString;
            while ((currentString = reader.readLine()) != null) {
                Matcher cidMatcher = cidPattern.matcher(currentString);
                if (cidMatcher.find()){
                    // group返回匹配到的子字符串列表，正则表达式中加()的部分会被单独匹配出来
                    // group(0)是匹配到的整个字符串，group(1)就是匹配出来的(.*)，也就是cid
                    cid = cidMatcher.group(1);
                }
                Matcher addressMatcher = addressPattern.matcher(currentString);
                if (addressMatcher.find()){
                    address = addressMatcher.group(1);
                }
            }
            JSONObject infoList = new JSONObject();
            infoList.put("address",address);
            infoList.put("cid",cid);
            return infoList;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public boolean infoCheck(JSONObject info){
        String address = (String) info.get("address");
        String cid = (String) info.get("cid");
        return !address.equals("")&&!cid.equals("");
    }
}
